import {
    request
} from '../../request/index'
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({
    data: {
        tabs: [{
                id: 0,
                value: "综合",
                isActive: true
            },
            {
                id: 1,
                value: "销量",
                isActive: false
            },
            {
                id: 2,
                value: "价格",
                isActive: false
            }
        ],
        goodsList: [],
        
    },
    // 接口要的参数
    queryParams: {
        query: "",
        cid: 5,
        pagenum: 1,
        pagesize: 10
    },
    totalPages: 1,

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.queryParams.cid = options.cid.split("'")[1] || '';
        console.log(options);
        this.getGoodsList();
    },
    //获取商品列表的数据
   
    async getGoodsList() {
        console.log(this.queryParams.cid);
        const res = await request({
            url: '/goods/search',
            data:this.queryParams,
            // data: {
            //     query: "",
            //     cid: this.queryParams.cid,
            //     pagenum: 1,
            //     pagesize: 10
            // }
        })

        // 获取  总条数
        const total = res.data.message.total;
        console.log(total);
        // 计算总页数
        this.totalPages = Math.ceil(total / this.queryParams.pagesize);
        console.log('this.totalPages', this.totalPages)
        this.setData({
            // 拼接了数组
            // goodsList: res.data.message.goods,
            goodsList: [...this.data.goodsList, ...res.data.message.goods]
        })
        wx.stopPullDownRefresh()
        // 关闭下拉刷新的窗口如果没有调用下拉刷新的窗口直接关闭也不会报错
        setTimeout(function () {
            wx.stopPullDownRefresh({})
        }, 300)

    },
    //标题点击事件
    handleTabsItemChange(e) {
        //获取被点击的标题的索引
        console.log(e.detail);
        const {
            index
        } = e.detail;
        //修改原数组
        let {
            tabs
        } = this.data;
        tabs.forEach((v, i) => i === index ? v.isActive = true : v.isActive = false)
        this.setData({
            tabs
        })
    },
    //页面上滑 滚动条触底事件
    onReachBottom() {
        if (this.queryParams.pagenum >= this.totalPages) {
            wx.showToast({
                title: '没有下一页数据了',
            })
        } else {
            this.queryParams.pagenum++,
                this.getGoodsList()
            console.log('还有数据');
        }
    },
    // 下拉刷新事件
    onPullDownRefresh() {
        // 重置数组
        this.setData({
            goodsList: [],
        })
        //    重置页码
        this.queryParams.pagenum = 1;
        //发送请求
        this.getGoodsList();
    }

})